package cn.goktech.sports.modules.importDataone.schedule;


import cn.goktech.sports.modules.importDataone.dao.HeaderFuelMapper;
import cn.goktech.sports.modules.importDataone.entity.HeaderFuelEntity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
//@RestController
public class GetAllPriceOfSurchargeTask {

    @Autowired(required = false)
    private HeaderFuelMapper headerFuelMapper;

//    @RestAnon
//    @Scheduled(cron = "0/10 * * * * ?")
    /*@Scheduled(cron = "0 5 0 ? * MON")
    private void configureTasks() throws IOException {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        *//**
         * 定时任务每周一上午凌晨12：05分获取
         * 分别获取UPS、DHL对应的费率或价格
         * 将获取到的价格存入数据库中
         *//*
        InsertOrUpdateUSDPrice();
        InsertOrUpdateDHLPrice();
        insertPersentInfo();
        System.out.println("定时任务执行结束:"+"configureTasks");
    }*/
    //每月的1号凌晨5点获取Dhl的费率，并更改数据库数据费率
    @Scheduled(cron = "0 0 05 1 * ?")
    private void dhlMothTasks(){
        try {
            StringBuilder sb = new StringBuilder();
            //DHL官网地址
            String url = "https://www.5idhl.com/express/fuelSurchargeSearchAction.action";
            //请求并解析
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)urlObj.openConnection();
            conn.setDoInput(true);
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"))){
                String tmpLine;
                while((tmpLine = reader.readLine()) != null){
                    sb.append(tmpLine);
                }
            }
            conn.disconnect();
            /**
             * jsoup处理获取到的html格式文件
             */
            Document doc = Jsoup.parse(sb.toString());
            Elements elements = doc.getElementsByTag("tr");
            Iterator<Element> iterator = elements.iterator();
            String value = "";
            while(iterator.hasNext()){
                Element next = iterator.next();
                //取出网页上的时间
                Node yearMonth = next.child(1).childNode(0);
                //得到当前年月
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                String format = sdf.format(new Date());
                //判断年月是否为当前的年月
                if (StringUtils.isNotBlank(yearMonth.toString())&&format.equals(yearMonth.toString())){
                    //是当前月份取出费率-得到的是 18.75%
                    Node node = next.child(2).childNode(0);
                    //转为字符串
                    value = node.toString();
                    //把百分号替换为空，只保留数字，转为float除以100加上1就是  1.1875 字样
                    float v = Float.valueOf(value.replace("%","")) / 100 + 1;
                    //转为String更改数据库
                    //DHL产品类型为
                    headerFuelMapper.updateDHLRate("5",String.valueOf(v));
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    /**
     * 插入或更新 UPS价格
     * @throws IOException
     */
    private void InsertOrUpdateUSDPrice() throws IOException {
        //获取UPS,拿到price后进行费率换算成中国汇率，将中国汇率存入数据库
        URL url = new URL("https://www.ups.com/assets/resources/fuel-surcharge/cn.json");
        String usdPrice = getUSDPrice(getURLInfo(url));
//        URL url2 = new URL("http://m.59178.com/CNY/INC/GET.ASP?num="+usdPrice+"&FROM=USD&TOO=CNY&callback=jisuanjieguo");
//        String urlInfo = getURLInfo(url2).trim();
//        String jsonInfo = urlInfo.substring(13, urlInfo.length() - 1);
//        String hb = JSONObject.parseObject(jsonInfo).getString("duihuanhuobi").trim();
//        String chinesePrice = hb.substring(0, hb.length() - 8);
        String chinesPrice = this.getChinesPrice(usdPrice);
        addOrUpdateInfo(chinesPrice,"UPS");
    }

    /**
     * 添加或者更新价格
     * @param chinesePrice
     */
    private void addOrUpdateInfo(String chinesePrice,String fuelType) {
        HeaderFuelEntity headerFuelEntity = new HeaderFuelEntity();
        headerFuelEntity.setFuelType(fuelType);
        headerFuelEntity.setPrice(Double.parseDouble(chinesePrice));
        headerFuelEntity.setRate(0.0);
        HeaderFuelEntity resModel = headerFuelMapper.ifExistFirstInfo(fuelType);
        if(null == resModel|| resModel.getFuelId() <=0 ){
            headerFuelEntity.setGmtCreate(new Date());
            headerFuelEntity.setGmtModified(null);
            System.out.println();
            headerFuelMapper.saveInfo(headerFuelEntity);
        }else{
            headerFuelEntity.setGmtModified(new Date());
            headerFuelEntity.setFuelId(resModel.getFuelId());
            headerFuelMapper.updateInfo(headerFuelEntity);
        }
    }

    private void insertPersentInfo() {
        HeaderFuelEntity headerFuelEntity = new HeaderFuelEntity();
        headerFuelEntity.setFuelType("FEDEX");
        headerFuelEntity.setPrice(0.0);
        headerFuelEntity.setRate(1.06);
        HeaderFuelEntity resModel = headerFuelMapper.ifExistFirstInfo("FEDEX");
        if(null == resModel|| resModel.getFuelId() <=0 ){
            headerFuelEntity.setGmtCreate(new Date());
            headerFuelEntity.setGmtModified(null);
            headerFuelMapper.saveInfo(headerFuelEntity);
        }else{
            headerFuelEntity.setGmtModified(new Date());
            headerFuelEntity.setFuelId(resModel.getFuelId());
            headerFuelMapper.updateInfo(headerFuelEntity);
        }
    }

    /**
     * 插入或更新 DHL价格
     * @throws IOException
     */
    private void InsertOrUpdateDHLPrice() throws IOException {
        /**
         * 1.发起http请求，获取链接对应的数据
         * 2.获取到数据使用jsoup解析html获取到对应节点的数据保存在resStr中
         * 3.将数据进行汇率转换
         * 4.保存数据到数据库中
         */
        //获取UPS,拿到price后进行费率换算成中国汇率，将中国汇率存入数据库
        try {
            StringBuilder sb = new StringBuilder();
            String url = "http://www.cn.dhl.com/zh/express/shipping/shipping_advice/express_fuel_surcharge_apem.html";
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)urlObj.openConnection();
            conn.setDoInput(true);
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"))){
                String tmpLine;
                while((tmpLine = reader.readLine()) != null){
                    sb.append(tmpLine);
                }
            }
            conn.disconnect();
            /**
             * jsoup处理获取到的html格式文件
             */
            Document doc = Jsoup.parse(sb.toString());
            Elements elements = doc.getElementsByTag("tr");
            Iterator<Element> iterator = elements.iterator();
            String value = "";
            String resStr = "";
            while(iterator.hasNext()){
                Node node = iterator.next().child(1).childNode(0);
                value = node.toString();
                char[] chars = value.toCharArray();
                if(null != value && null != chars && chars.length>0){
                    if(chars[0] == '$'){
                        resStr = value.substring(1);
                        break;
                    }
                }
            }
            /**
             * 如果resStr不为空，则转换汇率，再进行数据库插入操作，否则未获取到数据
             */
            if(null != resStr && resStr.length()>0){
                String chinesePrice = getChinesPrice(resStr);
                addOrUpdateInfo(chinesePrice,"DHL");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 通过美元获取实时汇率计算对应人民币价格
     * @param resStr
     * @return
     * @throws IOException
     */
    private String getChinesPrice(String resStr) throws IOException {
        StringBuilder sbFL = new StringBuilder();
        URL getFL = new URL("http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4");
        HttpURLConnection connectionFL = (HttpURLConnection)getFL.openConnection();
        connectionFL.setDoInput(true);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connectionFL.getInputStream(),"UTF-8"))){
            String tmpLine;
            while((tmpLine = reader.readLine()) != null){
                sbFL.append(tmpLine);
            }
        }
        connectionFL.disconnect();

        String rate = JSONObject.parseObject(sbFL.toString()).getJSONObject("result").getString("rate");
        Double res = Double.parseDouble(rate)*Double.parseDouble(resStr);
        BigDecimal bigDecimal = new BigDecimal(Double.valueOf(res)).setScale(2,BigDecimal.ROUND_HALF_UP);
        return bigDecimal+"";
    }


    /**
     * 打开HTTP连接
     * 获取URL信息
     * @param url
     * @return
     * @throws IOException
     */
    private String getURLInfo(URL url) throws IOException {
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36");
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        out.flush();
        out.close();
        String sCurrentLine;
        String sTotalString = "";
        InputStream l_urlStream = connection.getInputStream();
        BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));
        while ((sCurrentLine = l_reader.readLine()) != null){
            sTotalString += sCurrentLine + "\r\n";
        }
        return sTotalString;
    }

    /**
     * 获取美元价格
     * @param sTotalString
     * @return
     */
    private String getUSDPrice(String sTotalString) {
        JSONArray jsonArray = JSONObject.parseObject(sTotalString.toString())
                .getJSONObject("FuelSurchargeResponse")
                .getJSONObject("FuelSurchargeRates_en")
                .getJSONArray("USGCJetFuel");
        String field2 = jsonArray.getJSONObject(0).getString("Field2");
//        System.out.println("价格：");
//        System.out.printf(field2.split(" ")[1]);
//        System.out.println("");
        return field2.split(" ")[1];
    }


}
